﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using LView.CMS.IServices;
using LView.CMS.ViewModels;
using SQLBuilder.Core.Repositories;
using AutoMapper;
using LView.CMS.Models;
using LView.CMS.Core;
using LView.CMS.Core.Extensions;
using System.Linq;

namespace LView.CMS.Services
{
    public class TaskService : ITaskService
    {
        private readonly IMapper _mapper;
        private readonly IRepository _repository;
        private readonly IManagerService _managerService;
        public TaskService(Func<string, IRepository> hander, IMapper mapper, IManagerService managerService)
        {
            _repository = hander(null);
            _mapper = mapper;
            _managerService = managerService;
        }

        public async Task<TableDataModel> LoadDataAsync(PageModel model)
        {
            var (recordList, recordCount) = (await MongodbHelper.Instance.FindListAsync<LTask>(
                sort: (x => x.Id),
                isDesc: true,
                pageIndex: model.Page,
                pageSize: model.Limit));

            return new TableDataModel
            {
                count = (int)recordCount,
                data = recordList,
            };
        }

        public async Task<BaseResult> AddOrModifyAsync(TaskAddOrModifyModel model)
        {
            var result = new BaseResult();
            if (model.Id.IsNullOrEmpty())
            {
                await MongodbHelper.Instance.InsertOneAsync<LTask>(new LTask
                {
                    Id = Guid.NewGuid().ToString(),
                    Name = model.Name,
                    DIR = model.DIR,
                    Description = model.Description,
                    CreateUserId = model.CreateUserId,
                    CreateUserName = model.CreateUserName,
                    CreateDate = DateTime.Now,
                    EndDate = (DateTime)model.EndDate,
                    Type = 0
                });
                result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
            }
            else
            {
                var OriTaskData = MongodbHelper.Instance.FindEntity<LTask>(x => x.Id == model.Id);
                //await MongodbHelper.Instance.DeleteOneAsync<LTask>(x => x.Id == model.Id);
                if (OriTaskData != null)
                {
                    OriTaskData.Name = model.Name;
                    OriTaskData.Description = model.Description;
                    OriTaskData.EndDate = (DateTime)model.EndDate;
                    await MongodbHelper.Instance.UpdateOneAsync<LTask>(x => x.Id == OriTaskData.Id, OriTaskData);
                    //await MongodbHelper.Instance.InsertOneAsync<LTask>(OriTaskData);
                    result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                }
                else
                {
                    result.ResultCode = ResultCodeAddMsgKeys.CommonFailNoDataCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonFailNoDataMsg;
                }
            }
            return result;
        }

        public async Task<BaseResult> SendTaskAsync(string taskId, string taskName, string assignUser, string roleId)
        {
            var result = new BaseResult();
            try
            {
                var managerList = await _managerService.GetManagerByRoleid(roleId);
                var taskEntity = await MongodbHelper.Instance.FindEntityAsync<LTask>(x => x.Id == taskId);
                var categorySum = taskEntity.Category?.Count; ;
                var courseSum = new List<Course>();
                taskEntity.Category?.ForEach(x =>
                {
                    x.Course?.ForEach(p => { courseSum.Add(p); });
                });
                if (taskEntity.Category?.Count > 0 && courseSum.Count > 0)
                {
                    await MongodbHelper.Instance.DeleteOneAsync<LTask>(x => x.Id == taskId);
                    managerList.ToList().ForEach(async x =>
                    {
                        var myTask = new LMyTask
                        {
                            Id = Guid.NewGuid().ToString(),
                            UserId = x.Id,
                            UserName = x.UserName,
                            TaskId = taskId,
                            Name = taskName,
                            AssignUserName = assignUser,
                            AssignDate = DateTime.Now,
                            Percent = 0,
                            Status = 0
                        };
                        await MongodbHelper.Instance.InsertOneAsync<LMyTask>(myTask);
                        var lprocess = new List<LProcess>();
                        taskEntity.Category.ForEach(category =>
                        {
                            if (category.Course?.Count > 0)
                            {
                                category.Course.ForEach(course =>
                                {
                                    lprocess.Add(new LProcess
                                    {
                                        CourseId = course.CourseId,
                                        Id = Guid.NewGuid().ToString(),
                                        Percent = 0,
                                        TaskId = taskId,
                                        UserId = x.Id
                                    });
                                });
                            }
                        });
                        await MongodbHelper.Instance.InsertManyAsync(lprocess);
                    });

                    taskEntity.Type = 1;
                    //await MongodbHelper.Instance.UpdateOneAsync<LTask>(x => x.Id == taskId, taskEntity);
                    await MongodbHelper.Instance.InsertOneAsync<LTask>(taskEntity);
                    result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                }
                else
                {
                    result.ResultCode = ResultCodeAddMsgKeys.CommonFailNoDataCode;
                    result.ResultMsg = "任务内无任何教程";
                }

            }
            catch (Exception ex)
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg + $":{ex.Message}";
            }
            return result;
        }

        public async Task<BaseResult> DeleteIdsAsync(string[] Ids)
        {
            var result = new BaseResult();
            await MongodbHelper.Instance.DeleteManyAsync<LTask>(x => Ids.Contains(x.Id));
            result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
            result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
            return result;
        }

        public async Task TaskDataForMongodbTest()
        {
            await MongodbHelper.Instance.InsertManyAsync<LTask>(new List<LTask>()
            {
                new LTask{
                    Id=Guid.NewGuid().ToString(),
                    Name="新型冠状病毒肺炎防控知识培训",
                    Description="2019年12月以来，新型冠状病毒肺炎迅速蔓延至全国各地。为加强立讯同仁的防控意识与防控能力，特设置本次培训。全员参与，群防群控，为了您的安全与健康，请认真完成本次培训。",
                    CreateDate=DateTime.Now,
                    CreateUserId="6345939F-AD8B-46EF-B221-4BB1D83519F3",
                    CreateUserName="霓虹下的野鬼",
                    EndDate=DateTime.Now.AddDays(20),
                    DIR="6345939F-AD8B-46EF-B221-4BB1D83519F3"
                },new LTask{
                    Id=Guid.NewGuid().ToString(),
                    Name="员工手册学习培训",
                    Description="暂无简介",
                    CreateDate=DateTime.Now,
                    CreateUserId="6345939F-AD8B-46EF-B221-4BB1D83519F3",
                    CreateUserName="霓虹下的野鬼",
                    EndDate=DateTime.Now.AddDays(20),
                    DIR="6345939F-AD8B-46EF-B221-4BB1D83519F3"
                }
            });
        }
    }
}
